<?php
/**
 * gbk编码字符转换到拼音首字母
 * @param        $text
 * @param string $exp
 * @return string
 */
function gb2py2($text, $exp = '') {
	if (preg_match('/[0-9]/is', $text)) return $text;
	if(!$text) return '';
	if(strtolower(DT_CHARSET) != 'gbk') $text = Str::convert($text, DT_CHARSET, 'gbk');
	$data = array();
	$tmp = @file(DT_ROOT.'/file/table/gb-pinyin.table');
	if(!$tmp) return '';
	$tmps = count($tmp);
	for($i = 0; $i < $tmps; $i++) {
		$tmp1 = explode("	", $tmp[$i]);
		$data[$i]=array($tmp1[0], $tmp1[1]);
	}
	$r = array();
	$k = 0;
	$textlen = strlen($text);
	for($i = 0; $i < $textlen; $i++) {
		$p = ord(substr($text, $i, 1));
		if($p > 160) {
			$q = ord(substr($text, ++$i, 1));
			$p = $p*256+$q-65536;
		}
		if($p > 0 && $p < 160) {
			$r[$k] = chr($p);
		} elseif($p< -20319 || $p > -10247) {
			$r[$k] = '';
		} else {
			for($j = $tmps-1; $j >= 0; $j--) {
				if($data[$j][1]<=$p) break;
			}
			$r[$k] = $data[$j][0];
		}
		$k++;
	}
	$fk = '';
	foreach($r as $v) {
		$fk .= substr($v, 0, 1);
	}
	return $fk;
}

function str2array($str) {
	$array = array();
	while (strlen($str)>0) {
		$strTest = decbin(ord(substr($str, 0, 1)));
		$strTest = str_pad($strTest, 8, '0', STR_PAD_LEFT);

		if (preg_match('/0[10]{7}/s', $strTest, $matches)) {
			$byteNum = 1;
		} elseif(preg_match('/110[10]{5}/s', $strTest, $matches)){
			$byteNum = 2;
		} elseif(preg_match('/1110[10]{4}/s', $strTest, $matches)){
			$byteNum = 3;
		} elseif(preg_match('/11110[10]{3}/s', $strTest, $matches)){
			$byteNum = 4;
		}
		array_push($array, substr($str, 0, $byteNum));
		$str = substr($str, $byteNum);
	}
	return $array;
}
function str2py($str) {
	$strArray = str2array($str);
	$py = '';
	foreach($strArray as $char) {
		$pyi = gb2py2($char);
		if (!$pyi) {
			$pinyin = substr(stranger2py('pinyin.txt', $char), 0, 1);
			if ($pinyin) {
				$pyi = substr($pinyin, 0, 1);
			} else {
				exit(var_dump($char));
			}
		}
		$py .= $pyi;
	}
	return $py;
}
function stranger2character($file,$char)
{
	$str = file_get_contents($file);
	if (preg_match("/{$char}\-([a-z]{1})/is",$str,$match)) {
		return $match[1];
	} else {
		file_put_contents($file, $str."\n".$char);
		return false;
	}
}

function stranger2py($file,$char)
{
	$str = file_get_contents($file);
	if (preg_match("/{$char}([a-z ]{1,15})/is",$str,$match)) {
		return $match[1];
	} else {
		return false;
	}
}

function area2areaid($areaname) {
	global $AREA;
	$areaid = 0;
	foreach ($AREA as $area) {
		if (preg_match("/.*?{$areaname}.*?/is", $area['areaname'])) {
			return $area['areaid'];
		}
	}
	return $areaid;
}

?>